package code16_thread;

public class Test07 {
	public static Object obj = new Object();// 锁对象
	public static void main(String[] args) {
		// 让 Worker1与Worker2 交替输出 1、2。
		Worker1 w1 = new Worker1();
		Worker2 w2 = new Worker2();
		w1.start();
		// 确保 1 先输出
		try {
			Thread.sleep(500);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		w2.start();
	}
	
}
class Worker1 extends Thread {
	public void run() {
		while(true) {
			// 不停地输出 1, 每输出一次休息(sleep) 500ms
			synchronized (Test07.obj) {
				System.out.println("1");
				try {
					Test07.obj.notify();// 唤醒对手
					Test07.obj.wait();// 自己等待
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}
class Worker2 extends Thread {
	public void run() {
		while(true) {
			// 不停地输出 2, 每输出一次休息(sleep) 500ms
			synchronized (Test07.obj) {
				System.out.println("2");
				Test07.obj.notify();// 唤醒对手
				try {
					Test07.obj.wait();// 自己等待
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}